package com.hospital.search.module.message.consumer;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hospital.common.dto.search.module.PostInsertDto;
import com.hospital.common.dto.search.module.ReplyInsertDto;
import com.hospital.search.module.exception.SearchServiceException;
import com.hospital.search.module.exception.enums.SearchServiceExpCode;
import com.hospital.search.module.message.Message;
import com.hospital.search.module.service.SearchService;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

@Component
@RocketMQMessageListener(
        topic = "${topic.elastic-insert-topic}",
        consumerGroup = "${rocketmq.consumer.group}",
        messageModel = MessageModel.CLUSTERING
)
public class ElasticInsertConsumer implements RocketMQListener<Message> {
    @Autowired
    private SearchService searchService;
    @Override
    public void onMessage(Message message) {
        if(ObjectUtils.isEmpty(message.getData())||ObjectUtils.isEmpty(message.getType())){
            throw new SearchServiceException(SearchServiceExpCode.MESSAGE_ERROR);
        }
        switch (message.getType()){
            case POST:
                try {
                    PostInsertDto postInsertDto = new ObjectMapper().convertValue(message.getData(), PostInsertDto.class);
                    searchService.insertPost(postInsertDto);
                }catch (Exception e){
                    if(e instanceof SearchServiceException exception){
                        throw exception;
                    }else{
                        throw new SearchServiceException(SearchServiceExpCode.MESSAGE_TYPE_ERROR);
                    }
                }
                break;
            case REPLY:
                try {
                    ReplyInsertDto replyInsertDto = new ObjectMapper().convertValue(message.getData(), ReplyInsertDto.class);
                    searchService.insertReply(replyInsertDto);
                }catch (Exception e){
                    if(e instanceof SearchServiceException){
                        throw (SearchServiceException) e;
                    }else{
                        throw new SearchServiceException(SearchServiceExpCode.MESSAGE_TYPE_ERROR);
                    }
                }
                break;
            default:
                throw new SearchServiceException(SearchServiceExpCode.MESSAGE_TYPE_ERROR);
        }
    }
}
